﻿using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RemoteManger
{
    public class SqlHelper
    {
        private static string defaultConfigId = "";
        /// <summary>
        /// 初始化数据库配置
        /// </summary>
        /// <exception cref="Exception"></exception>
        public static void Init()
        {
            try
            {
                string currentDirectory = Directory.GetCurrentDirectory(); // 获取当前程序所在目录
                string[] jsonFiles = Directory.GetFiles(currentDirectory, "*.json"); // 查询当前目录下的所有 JSON 文件
                ConfigurationBuilder builder = new ConfigurationBuilder();
                foreach (string file in jsonFiles)
                {
                    builder.AddJsonFile(file, optional: true, reloadOnChange: true);
                }
                IConfigurationRoot config = builder.Build();
                var list = config.GetSection("DataBaseConfigs").Get<List<DataBaseConfigs>>();
                Load(list);
            }
            catch (Exception ex)
            {
                throw new Exception("数据库json文件加载失败 " + ex.Message);
            }
        }
        /// <summary>
        /// 获取数据库实例
        /// </summary>
        /// <param name="configid"></param>
        /// <returns></returns>
        public static SqlSugarScopeProvider GetInstance(string configid = "default")
        {
            return _db.GetConnectionScope(configid.IsNullOrEmpty() ? defaultConfigId : configid);
        }
        private static SqlSugarScope _db = null;
        private static void Load(List<DataBaseConfigs> list)
        {
            if (_db == null)
            {
                List<ConnectionConfig> lis = new List<ConnectionConfig>();
                foreach (var item in list)
                {
                    lis.Add(new ConnectionConfig
                    {
                        ConfigId = item.ConfigId,
                        DbLinkName = item.DbLinkName,
                        ConnectionString = item.ConnectionString,//连接符字串
                        DbType = (SqlSugar.DbType)((int)item.DbType),//数据库类型
                        IsAutoCloseConnection = item.IsAutoCloseConnection //不设成true要手动close
                    });
                }
                //lis.Add(new ConnectionConfig
                //{
                //    ConfigId = "default",
                //    DbLinkName = "Remote",
                //    ConnectionString = item.ConnectionString,//连接符字串
                //    DbType = (SqlSugar.DbType)((int)item.DbType),//数据库类型
                //    IsAutoCloseConnection = item.IsAutoCloseConnection //不设成true要手动close
                //});

                _db = new SqlSugarScope(lis);
                defaultConfigId = list.FirstOrDefault().ConfigId;
            }
        }
    }
    public class DataBaseConfigs
    {
        public string DbLinkName { set; get; }
        public string ConfigId { set; get; }
        /// <summary>
        /// 数据库连接
        /// </summary>
        public string ConnectionString { set; get; }
        /// <summary>
        /// 数据库类型
        /// </summary>
        public DabaseType DbType { set; get; }
        /// <summary>
        /// 是否自动关闭连接
        /// </summary>
        public bool IsAutoCloseConnection { set; get; }


    }
    public enum DabaseType
    {
        MySql = 0,
        SqlServer = 1,
        Sqlite = 2,
        Oracle = 3,
        PostgreSQL = 4,
        Dm = 5,
        Kdbndp = 6,
        Oscar = 7,
        MySqlConnector = 8,
        Access = 9,
        OpenGauss = 10,
        QuestDB = 11,
        HG = 12,
        ClickHouse = 13,
        GBase = 14,
        Odbc = 0xF,
        OceanBaseForOracle = 0x10,
        TDengine = 17,
        GaussDB = 18,
        OceanBase = 19,
        Tidb = 20,
        Vastbase = 21,
        Custom = 900
    }
}
